from dbRoadsPoints import *
from common import *
import json

def read_json(data_file):
    roads = {}
    try:
        with open(data_file, encoding='utf-8') as file:
            content = json.load(file)
        if content:
            roads = content
        else:
            print("JSON 文件为空")
    except json.JSONDecodeError:
        print("文件内容不是有效的 JSON 格式")
    except FileNotFoundError:
        print("文件未找到")
    except Exception as e:
        print(f"发生未知错误: {e}")
    return roads


def findAndSaveEmissions(params,table_name,roads,save_dat):
    # 查找道路排放信息
    i = 0
    road_emissions = {}
    code_name = {}
    for road in roads: 
        road_info = {}
        road_name = road
        # info = roads[road_name]
        # print(info)
        new_params = params + (road_name,)
        road_info = findOne(new_params,table_name)
        road_emissions[road_name] = road_info
        code_name[road] = road_info['road_code']
        # print(road_emissions)
    if road_emissions:
        flag = saveToPTEMARB(roads,road_emissions,save_dat,params)
        if flag: 
            print(f"{save_dat} 保存成功")
            # output_file = "roadPrimary_code.json"
            # with open(output_file, 'w', encoding='utf-8') as file:
            #     json.dump(code_name, file,ensure_ascii=False)
            # print("数据已保存到", output_file)
            return True
        else:
            print("保存失败")
    else:
        print("没找到排放数据")
    return False


if __name__ == "__main__":
    data_file = "roadJingShiLu.json"
    save_dat = "roadpoint1.dat"
    roads = read_json(data_file)
    # print(roads)
    station_code = '370100910'
    start_date_time = '2024-10-30 00:00:00'
    end_date_time = '2024-10-30 23:00:00'
    # road_name = '经十东路'
    table_name = 'dwm_air_station_pygp_roads_h'
    params = (station_code, start_date_time, end_date_time)
    findAndSaveEmissions(params,table_name,roads,save_dat)

    # rs = findOne(params, table_name)
    # print(rs)